<Tree @ref="tree"
      ShowIcon DataSource="games"
      Multiple="@multiple"
      TitleExpression="x => x.DataItem.Text"
      ChildrenExpression="x => x.DataItem.Items"
      IconExpression="x => x.DataItem.Icon"
      IsLeafExpression="x => x.DataItem.Items?.Count == 0"
      KeyExpression="x => x.DataItem.Id"
      @bind-SelectedKey="@selectedKey"
      @bind-SelectedData="@selectedData"
      @bind-SelectedNode="@selectedNode"
      @bind-SelectedKeys="@selectedKeys"
      TItem="GameElement">
</Tree>

<Divider>Single</Divider>
<span>bind-SelectedKey:@selectedKey</span>
<br />
<span>bind-SelectedData:@(System.Text.Json.JsonSerializer.Serialize(selectedData))</span>
<br />
<span>bind-SelectedNode:@(System.Text.Json.JsonSerializer.Serialize(selectedNode?.Id))</span>
<Divider>Multiple</Divider>
<Switch @bind-Value="multiple" />Multiple
<br />
<span>bind-SelectedKeys:@(System.Text.Json.JsonSerializer.Serialize(selectedKeys))</span>
<Divider>Action</Divider>
<Button OnClick="AddSon">Add Son Node</Button>
<Button OnClick="DeleteNode">Delete Node</Button>

@code{

    private bool multiple;

    Tree<GameElement> tree;

    string selectedKey;

    GameElement selectedData;

    TreeNode<GameElement> selectedNode;

    string[] selectedKeys;


    void AddSon()
    {
        if (selectedNode != null)
        {
            var id = new Random().Next(1000).ToString();
            selectedNode.DataItem.Items.Add(new GameElement(id, $"Node {id}")
            {
                Items = new List<GameElement>()
            }); ;

        }
    }

    void DeleteNode()
    {
        if (selectedNode != null)
        {
            if (selectedNode.ParentNode != null)
            {
                selectedNode.ParentNode.DataItem.Items.Remove(selectedNode.DataItem);
            }
            else
            {
                tree.DataSource.Remove(selectedNode.DataItem);
            }
            StateHasChanged();

        }
    }

    List<GameElement> games = new List<GameElement>()
{
        new ("100","XBox","windows")
        {
            Items=new List<GameElement>()
{
                new ("101","Halo"),
                 new ("102","Gears of War"),
                 new ("103","Forza Motosport"),
            }
        },
        new ("200","PlayStation","desktop")
        {
            Items=new List<GameElement>()
{
                new ("201","Uncharted"),
                 new ("202","God Of War"),
                 new ("203","The Order:1886"),
            }
        },
                new ("300","Switch","mobile")
        {
            Items=new List<GameElement>()
{
                new ("301","Super Mario Bros"),
                 new ("302","The Legend of Zelda"),
            }
        }
    };

    private record GameElement(string Id, string Text, string Icon = null)
    {
        public List<GameElement> Items { get; set; } = new List<GameElement>();
    }
}